package kr.co.sdworld.webclient.spring.controller;

import java.io.File;
import java.util.Map;

import kr.co.sdworld.api.apns.model.ApnsCert;
import kr.co.sdworld.api.apns.model.ApnsLogin;
import kr.co.sdworld.api.apns.service.CertService;
import kr.co.sdworld.common.util.GlobalConfig;
import kr.co.sdworld.webs.ServiceContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class CT_Upload 
{
	@Autowired
	private CertService certService;
	
	@RequestMapping(value="/upload.sd")
	public ModelAndView upload(MultipartHttpServletRequest request)
	{
		ModelAndView mnv = new ModelAndView("jsonView");

		Map<String, MultipartFile> files = request.getFileMap();
	    CommonsMultipartFile cmf = (CommonsMultipartFile) files.get("certFile");

	    ApnsLogin login = (ApnsLogin)ServiceContext.getSession().getAttribute("login");
	    String repoPath = GlobalConfig.getProperty("apns.cert.uploadPath") + "/" + login.getUserId();
	    
	    File directoryForCheck = new File(repoPath);
	    if(!directoryForCheck.exists()) {
	    	directoryForCheck.mkdirs();
	    }
	    
	    String appId = request.getParameter("appId");
	    String certPass = request.getParameter("certPass");
	    String certPath = repoPath + "/" + cmf.getOriginalFilename();
	    
	    ApnsCert apnsCert = certService.saveCert(appId, certPath, certPass);
	    
	    if(apnsCert != null)
	    {
	    	try {
		    	File f = new File(certPath);
			    cmf.transferTo(f);
			    mnv.addObject("file", "ok");
			} catch (Exception e) {
				e.printStackTrace();
				mnv.addObject("file", "not ok..-_-");
			}
	    }
	    else
	    {
	    	mnv.addObject("file", "not ok..-_-");
	    }
	    
		return mnv;
	}
}
